/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cuong.bean;

import client.entity.Account;
import client.entity.Cv;
import client.entity.Recruitment;
import client.entity.SaveCv;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import util.HibernateUtil;

/**
 *
 * @author Admin Windows 8
 */
@ManagedBean
@SessionScoped
public class SaveMyCV {

    private String status = "fail";

    public SaveMyCV() {
    }

    public String saveCVAction() {
        String param = getParam("idCV");
        Account ac = (Account) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("account");
        if (ac == null) {
            return "login.xhtml?faces-redirect=true";
        } else {
            if (param == null) {
                param = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("idCV");
            } else {
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("idCV", param);
            }
            if (ac.getRole() == false) {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "You are not Employment", "Please Try Again");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } else {
                SessionFactory factory = HibernateUtil.getSessionFactory();
                Session ss = factory.openSession();
                ss.getTransaction().begin();
                SaveCv saveCV = new SaveCv();
                Cv cv = (Cv) ss.createQuery("from Cv cv where cv.id=" + Integer.parseInt(param)).uniqueResult();
                saveCV.setAccount(ac);
                saveCV.setCv(cv);
                ss.save(saveCV);
                ss.getTransaction().commit();
                ss.close();
                status = "true";
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Information", "Save CV Success");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public String getParam(String param) {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        return params.get(param);
    }
}
